package com.ys.service.storage.impl;

import java.math.BigDecimal;
import java.util.*;

import com.ys.config.MenuId;
import com.ys.entity.hr.ThrOperateCompanyApply;
import com.ys.enume.finance.TcwOperateFrozenRunningEnum;
import com.ys.enume.storage.TccDistributeEnum;
import com.ys.mapper.storage.TccAllocateDetailMapper;
import com.ys.service.sys.CommonApiService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.constant.AppConstant;
import com.ys.dto.AddDto;
import com.ys.entity.flow.YspModel;
import com.ys.entity.storage.TccAllocate;
import com.ys.entity.storage.TccAllocateDetail;
import com.ys.entity.storage.TccDistribute;
import com.ys.entity.storage.TccDistributeDetail;
import com.ys.entity.storage.TccStockControl;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsMenu;
import com.ys.entity.sys.YsProcInst;
import com.ys.enume.base.TransactionTypeEnum;
import com.ys.enume.flow.FlowEnum;
import com.ys.enume.flow.YsProcInstEnum;
import com.ys.enume.storage.TccAllocateEnum;
import com.ys.enume.storage.TccStockFrozenRunningEnum;
import com.ys.enume.storage.TccStockSourceEnum;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.storage.TccDistributeDetailMapper;
import com.ys.mapper.storage.TccDistributeMapper;
import com.ys.service.business.TcwAccountDetailedForCompanyService;
import com.ys.service.finance.TcwAccountCountForCompanyService;
import com.ys.service.flow.YspTaskService;
import com.ys.service.storage.TccDistributeService;
import com.ys.service.storage.TccStockControlService;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.Flow;
import com.ys.vo.R;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service("tccDistributeService")
public class TccDistributeImpl implements TccDistributeService {

	private static final Logger logger = LoggerFactory.getLogger(TccDistributeImpl.class);

	@Autowired
	private StorageMapper storageMapper;
	@Autowired
	private TccDistributeMapper tccDistributeMapper;
	@Autowired
	private TccDistributeDetailMapper tccDistributeDetailMapper;
	@Autowired
	private TcwAccountCountForCompanyService tcwAccountCountForCompanyService;
	@Autowired
	private TcwAccountDetailedForCompanyService tcwAccountDetailedForCompanyService;
	@Autowired
	private TccStockControlService tccStockControlService;
	@Autowired
	private YspTaskService yspTaskService;
	@Autowired
	private TccAllocateDetailMapper tccAllocateDetailMapper;
	@Autowired
	private CommonApiService<TccDistribute> commonApiService;
	
	@Override
	@Transactional
	public R add(String bid, Integer type, String detailArr, Long menuId, String vgsbm,String vbz) throws Exception {
		
		// 验证订单号
		if (new TccDistribute().setBid(bid).count() > 0) {
			return R.error("该订单号已存在");
		}
		
		// 验证详情
		JSONArray detailJA = JSON.parseArray(detailArr);
		R r = checkDetailJA(detailJA,vgsbm);
		if (r.getCode() == R.Code.FAILED.value) {
			return r;
		}
		
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		
		// 验证库存数据
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			Long stockControlId = detailJO.getLong("stockControlId");
			String vgsbmFrom = detailJO.getString("vgsbmFrom");
			if(new TccStockControl().setId(stockControlId).setVgsbm(vgsbmFrom).count() == 0) {
				return R.error("只能从调出运营公司下的库存调取");
			}
		}
		
		// 添加手工分配单
		TccDistribute entity = null;
		{
			Integer effectStock = FlowEnum.EffectStock.NOT_EFFECT.value;
			Long createChangeId = tsUserChange.getId();
			entity = TccDistribute.tccDistribute(bid, effectStock, type, vgsbm,vbz,createChangeId,1);
		}
		tccDistributeMapper.insert(entity);
		
		// 添加手工分配单明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			String bidDistribute = entity.getBid();
			Long allocateDetailId = detailJO.getLong("allocateDetailId");
			Long stockControlId = detailJO.getLong("stockControlId");
			Integer stockNumAll = detailJO.getInteger("stockNumAll");
			Integer num = detailJO.getInteger("num");
			BigDecimal singlePrice = detailJO.getBigDecimal("singlePrice");
			TccDistributeDetail tccDistributeDetail = TccDistributeDetail.tccDistributeDetail(bidDistribute, allocateDetailId, stockControlId, stockNumAll, num, singlePrice, 1);
			tccDistributeDetailMapper.insert(tccDistributeDetail);

			//回填分配数量 判断是否已分配
			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(allocateDetailId).queryFirst();
			tccAllocateDetail.setDistributeNum(tccAllocateDetail.getDistributeNum() + num);
			tccAllocateDetail.setMayDistributeNum(tccAllocateDetail.getNum() - tccAllocateDetail.getDistributeNum() - tccAllocateDetail.getAllocateCancelNum());
			if (tccAllocateDetail.getNum() == tccAllocateDetail.getDistributeNum() + tccAllocateDetail.getAllocateCancelNum()){
				tccAllocateDetail.setStateDistribute(1);
			}
			tccAllocateDetailMapper.update(tccAllocateDetail);

			//冻结库存
			Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_ADD.value;
			String sourceBid = bid;
			Long sourceId = tccDistributeDetail.getId();
			tccStockControlService.frozen(tccDistributeDetail.getStockControlId(), tccDistributeDetail.getNum(), sourceType, sourceBid, sourceId);
		}
		
		/*
		 * 流程初始化
		 */
		YsMenu ysMenu = new YsMenu().setId(menuId).queryFirst();
		if (ysMenu.getFlowModelId().longValue() != 0L) {
			YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
			String codeModel = yspModel.getCode();
			String createUserId = ShiroUtils.getUserId();
			yspTaskService.init(codeModel, bid, createUserId);
		}
		
		return R.ok(AddDto.gotoEdit("/web/storage/tccDistribute/toFlow?bid=" + entity.getBid()));
	}
	
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R edit(String bid, String detailArr, Long menuId, String vgsbm,String vbz) throws Exception {
		
		Integer stateFlow = yspTaskService.flowState(bid);
		if (stateFlow != YsProcInstEnum.StateFlow.INIT.value) {
			return R.error("非制单中数据，无法修改");
		}
		
		// 验证是否制单人
		YsProcInst entity = new YsProcInst().setBid(bid).queryFirst();
		if (!entity.getCreateUserId().equals(ShiroUtils.getUserId())) {
			return R.error("非制单人无法修改");
		}

		//回填所有的手工分配单数据
		List<TccDistributeDetail> tccDistributeDetailList = new TccDistributeDetail().setBidDistribute(bid).queryList();
		for (TccDistributeDetail tccDistributeDetail :tccDistributeDetailList){
			//删除分配数量 判断是否已分配
			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(tccDistributeDetail.getAllocateDetailId()).queryFirst();
			tccAllocateDetail.setDistributeNum(tccAllocateDetail.getDistributeNum() - tccDistributeDetail.getNum());
			tccAllocateDetail.setMayDistributeNum(tccAllocateDetail.getNum() - tccAllocateDetail.getDistributeNum() - tccAllocateDetail.getAllocateCancelNum());
			if (tccAllocateDetail.getNum() != tccAllocateDetail.getDistributeNum() + tccAllocateDetail.getAllocateCancelNum()){
				tccAllocateDetail.setStateDistribute(0);
			}
			tccAllocateDetailMapper.update(tccAllocateDetail);

			//冻结库存
			Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_DISTRIBUTE_FLOW_UPDATEJD.value;
			String sourceBid = bid;
			Long sourceId = tccDistributeDetail.getId();
			tccStockControlService.thaw(tccDistributeDetail.getStockControlId(), tccDistributeDetail.getNum(), sourceType, sourceBid, sourceId);
		}
		
		JSONArray detailJA = JSON.parseArray(detailArr);
		R r = checkDetailJA(detailJA,vgsbm);
		if (r.getCode() == R.Code.FAILED.value) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return r;
		}

		// 删除旧的手工分配单
		storageMapper.deleteBatchTccDistributeDetailByBid(bid);
		// 添加手工分配单明细
		for (int i = 0; i < detailJA.size(); i++) {
			JSONObject detailJO = detailJA.getJSONObject(i);

			String bidDistribute = bid;
			Long allocateDetailId = detailJO.getLong("allocateDetailId");
			Long stockControlId = detailJO.getLong("stockControlId");
			BigDecimal singlePrice = detailJO.getBigDecimal("singlePrice");
			Integer num = detailJO.getInteger("num");
			Integer stockNumAll = detailJO.getInteger("stockNumAll");
			TccDistributeDetail tccDistributeDetail = TccDistributeDetail.tccDistributeDetail(bidDistribute, allocateDetailId, stockControlId, stockNumAll, num, singlePrice, 1);
			tccDistributeDetailMapper.insert(tccDistributeDetail);

			//回填分配数量 判断是否已分配
			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(allocateDetailId).queryFirst();
			tccAllocateDetail.setDistributeNum(tccAllocateDetail.getDistributeNum() + num);
			tccAllocateDetail.setMayDistributeNum(tccAllocateDetail.getNum() - tccAllocateDetail.getDistributeNum() - tccAllocateDetail.getAllocateCancelNum());
			if (tccAllocateDetail.getNum() == tccAllocateDetail.getDistributeNum() + tccAllocateDetail.getAllocateCancelNum()){
				tccAllocateDetail.setStateDistribute(1);
			}
			tccAllocateDetailMapper.update(tccAllocateDetail);

			//冻结库存
			Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_DISTRIBUTE_FLOW_UPDATEDJ.value;
			String sourceBid = bid;
			Long sourceId = tccDistributeDetail.getId();
			tccStockControlService.frozen(tccDistributeDetail.getStockControlId(), tccDistributeDetail.getNum(), sourceType, sourceBid, sourceId);
		}
		
		return R.ok(AddDto.gotoEdit("/web/storage/tccDistribute/toFlow?bid=" + bid));
	}

	@Override
	@Transactional
	public R deleteTrue(Long id) throws Exception {
		if (id == null) {
			return R.error("ID不能为空");
		}
		TccDistribute entity = new TccDistribute().setId(id).queryFirst();
		if (entity.getEffectStock() == FlowEnum.EffectStock.EFFECTED.value) {
			return R.error("已生效数据无法删除");
		}
		// 验证是否制单人
		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setId(entity.getCreateChangeId()).queryFirst();
		
		if (!tsUserChange.getUserId().equals(loginUserId)) {
			return R.error("非制单人，无法删除");
		}
		
		// 删除主数据
		tccDistributeMapper.deleteTrue(id);
		
		// 删除子数据
		List<TccDistributeDetail> listDetail = new TccDistributeDetail().setBidDistribute(entity.getBid()).queryList();
		for(TccDistributeDetail tccDistributeDetail : listDetail) {
			//删除分配数量 判断是否已分配
			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(tccDistributeDetail.getAllocateDetailId()).queryFirst();
			tccAllocateDetail.setDistributeNum(tccAllocateDetail.getDistributeNum() - tccDistributeDetail.getNum());
			tccAllocateDetail.setMayDistributeNum(tccAllocateDetail.getNum() - tccAllocateDetail.getDistributeNum() - tccAllocateDetail.getAllocateCancelNum());
			if (tccAllocateDetail.getNum() != tccAllocateDetail.getDistributeNum() + tccAllocateDetail.getAllocateCancelNum()){
				tccAllocateDetail.setStateDistribute(0);
			}
			tccAllocateDetailMapper.update(tccAllocateDetail);

			//冻结库存
			Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_DISTRIBUTE_FLOW_UPDATEJD.value;
			String sourceBid = entity.getBid();
			Long sourceId = tccDistributeDetail.getId();
			tccStockControlService.thaw(tccDistributeDetail.getStockControlId(), tccDistributeDetail.getNum(), sourceType, sourceBid, sourceId);

			tccDistributeDetailMapper.deleteTrue(tccDistributeDetail.getId());
		}
		
		yspTaskService.flowDelete(entity.getBid(), loginUserId);
		return R.ok();
	}

	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R flowPass(Long id, String loginUserId) throws Exception {
		
		TccDistribute entity = new TccDistribute().setId(id).queryFirst();
		String bid = entity.getBid();
		
		// 若流程是初始化状态，需验证可用库存
		YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
		if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
			List<TccDistributeDetail> listTccDistributeDetail = new TccDistributeDetail().setBidDistribute(bid).queryList();
			for(TccDistributeDetail detail : listTccDistributeDetail) {
				TccStockControl tccStockControl = new TccStockControl().setId(detail.getStockControlId()).queryFirst();
				if (tccStockControl.getProductNumAll() < detail.getNum()) {
					return R.error("库存可用数量不足，无法流转");
				}
			}
		}
		
		
		try {
			Flow f = yspTaskService.flowPass(bid, loginUserId);
			if (f.getCode() == Flow.Code.FAILED.value) {
				return R.error(f.getMsg());
			} else {
				if (f.getState() == Flow.State.FINISH.value) {
					afterFlowFinish(id);
				}
				return R.ok();
			}
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return R.error("服务器正在开小差，请联系客服");
		}
	}

	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void afterFlowFinish(Long id) throws Exception {
		
		TccDistribute entity = new TccDistribute().setId(id).queryFirst();
		
		YsProcInst ysProcInst = new YsProcInst().setBid(entity.getBid()).queryFirst();
		if (ysProcInst.getStateFlow() != YsProcInstEnum.StateFlow.FINISH.value) {
			return;
		}
		
		entity.setEffectStock(FlowEnum.EffectStock.EFFECTED.value);
		tccDistributeMapper.update(entity);
		
		/*
		 *  调出方库存解冻并扣减
		 *  调入方库存新增
		 *  记录商品编码
		 */
		List<String> listProductCode = new ArrayList<String>();
		List<TccDistributeDetail> listTccDistributeDetail = new TccDistributeDetail().setBidDistribute(entity.getBid()).queryList();
		for(TccDistributeDetail detail : listTccDistributeDetail) {
			
			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(detail.getAllocateDetailId()).queryFirst();
			// 存入商品编码，用于后续统计更新精品的人次和销量
			String productCode = tccAllocateDetail.getProductCode();
			if (!listProductCode.contains(productCode)) {
				listProductCode.add(productCode);
			}
			
//			 变更预约调拨单分配状态
//			storageMapper.updateStateDistributeOfTccAllocateDetail(tccAllocateDetail.getId());

			// 调出方库存解冻并出库
			{
				Long stockControlId = detail.getStockControlId();
				Integer num = detail.getNum();
				Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_FINISH.value;
				String sourceBid = entity.getBid();
				Long sourceId = detail.getId();
				tccStockControlService.thaw(stockControlId, num, sourceType, sourceBid, sourceId);
			}
			{
				Long stockControlId = detail.getStockControlId();
				String remark = "手工分配单：" + entity.getBid();
				Integer numOut = detail.getNum();
				String bidRelative = entity.getBid();
				Integer sourceType = TccStockSourceEnum.Source.TCC_Distribute.value;
				Long sourceId = detail.getId();
				tccStockControlService.outWithRunning(stockControlId, remark, numOut, bidRelative, sourceType,sourceId);
			}
			
			// 调入方库存新增
			TccStockControl tccStockControlFrom = new TccStockControl().setId(detail.getStockControlId()).queryFirst();
			{
				String rkBid = tccStockControlFrom.getRkBid();
				String productName = tccStockControlFrom.getProductName();
				Integer productNum = detail.getNum();
				Integer productNumAll = detail.getNum();
				BigDecimal purchasePrice = tccStockControlFrom.getPurchasePrice();
				BigDecimal purchaseTotalPriceAll = tccStockControlFrom.getPurchaseTotalPriceAll();
				BigDecimal allotPrice = tccStockControlFrom.getAllotPrice();
				BigDecimal totalAllotPrice = tccStockControlFrom.getTotalAllotPrice();
				String vgsbm = tccAllocateDetail.getVgsbmTo();
				Date drksj = tccStockControlFrom.getDrksj();
				Integer isParent = TccStockSourceEnum.IsParent.YES.value;
				String chw = tccStockControlFrom.getChw();
				String companyVid = null;
				String sourceBid = entity.getBid();
				Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_FINISH.value;
				String remark = "手工分配单：" + sourceBid;
				String assembleBid = storageMapper.getAssembleBidByStockControlId(detail.getStockControlId());
				Long sourceId = id;
				tccStockControlService.inWithRunning(rkBid, chw, productName, productNum, productCode, productNumAll, purchasePrice, purchaseTotalPriceAll, allotPrice, totalAllotPrice, vgsbm, drksj, isParent, sourceBid, sourceType, remark, companyVid, assembleBid,sourceId);
			}
			
			// 调入方账户扣减
			Date now = new Date();
			{
				BigDecimal amount = tccAllocateDetail.getSinglePrice().multiply(new BigDecimal(detail.getNum()));

				try {
					// 解冻调入方账户
					tcwAccountCountForCompanyService.thaw(tccAllocateDetail.getVgsbmTo(), amount,
							TcwOperateFrozenRunningEnum.DocumentType.TCC_Distribute.value,
							detail.getId(),
							entity.getBid(),
							null);
				}catch (Exception e){
					logger.error("手工分配单解冻流水失败：" +e.getMessage(),e.getMessage(),e);
//					return;
				}

				// 扣减调入方账户余额
				String vGsBm = tccAllocateDetail.getVgsbmTo();
				String vGsBmP = tccAllocateDetail.getVgsbmFrom();
				String vJyLx = TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name;
				BigDecimal fJe = amount.negate();
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);
				
			}
			
			TccAllocate tccAllocate = new TccAllocate().setBid(tccAllocateDetail.getBidAllocate()).queryFirst();
			if (tccAllocate.getType() == TccAllocateEnum.Type.JING_PIN.value) {
				BigDecimal amount = BigDecimal.ONE.multiply(new BigDecimal(detail.getNum()));
	
				// 扣减调入方账户余额到仓储部
				String vGsBm = tccAllocateDetail.getVgsbmTo();
				String vGsBmP = AppConstant.STOCK_VGSBM;
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_ZZ.name;
				BigDecimal fJe = amount.negate();
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);
			}
			
			// 调出方账户入账
			{
				BigDecimal amount = detail.getSinglePrice().multiply(new BigDecimal(detail.getNum()));
				String vGsBm = tccAllocateDetail.getVgsbmFrom();
				String vGsBmP = tccAllocateDetail.getVgsbmTo();
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name;
				BigDecimal fJe = amount;
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);

				//当资金划入公司为GS0893运营中心，则需要将该库存的调拨价-采购价*1.05，划入GS0856
				if (vGsBm.equals("GS0893") && tccStockControlFrom.getPurchasePrice()!=null){
					ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm("GS0641").queryFirst();
					if (thrOperateCompanyApply == null){
						throw new RuntimeException("GS0641运营公司不存在!");
					}
					BigDecimal amountFw = (((detail.getSinglePrice().subtract(tccStockControlFrom.getPurchasePrice())).multiply(new BigDecimal(1.05))).multiply(new BigDecimal(detail.getNum()))).setScale(3, BigDecimal.ROUND_HALF_UP);
					vJyLx =  TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name;
					vGsBm = tccAllocateDetail.getVgsbmFrom();
					vGsBmP = thrOperateCompanyApply.getVgsbm();
					fJe = amountFw.negate();
					dJySj = now;
					dShSj = now;
					vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
					mName = null;
					mType = null;
					mNid = null;
					mBid = null;
					mGuid = null;
					writeTime = now;
					tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
							dShSj, vBz, entity.getBid(), writeTime);

					vGsBm = thrOperateCompanyApply.getVgsbm();
					vGsBmP = tccAllocateDetail.getVgsbmFrom();
					fJe = amountFw;
					tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
							dShSj, vBz, entity.getBid(), writeTime);
				}
				
			}
			if (tccAllocate.getType() == TccAllocateEnum.Type.JING_PIN.value) {
				BigDecimal amount = BigDecimal.ONE.multiply(new BigDecimal(detail.getNum()));
	
				// 仓储部组装费入账
				String vGsBm = AppConstant.STOCK_VGSBM;
				String vGsBmP = tccAllocateDetail.getVgsbmTo();
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_ZZ.name;
				BigDecimal fJe = amount;
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompany(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);
			}
			
		}
		
		// 统计精品的调拨总人次和调拨总数量
		for(String productCode : listProductCode) {
			storageMapper.updateTpBoutiqueNumBuyerAndNumSale(productCode);
		}
	}

	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void afterFlowFinish1(Long id) throws Exception {

		/*
		 *  调出方库存解冻并扣减
		 *  调入方库存新增
		 *  记录商品编码
		 */
		List<String> listProductCode = new ArrayList<String>();
		List<TccDistributeDetail> listTccDistributeDetail = new TccDistributeDetail().setId(id).queryList();
		for(TccDistributeDetail detail : listTccDistributeDetail) {

			TccDistribute entity = new TccDistribute().setBid(detail.getBidDistribute()).queryFirst();

			TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(detail.getAllocateDetailId()).queryFirst();
			// 存入商品编码，用于后续统计更新精品的人次和销量
			String productCode = tccAllocateDetail.getProductCode();
			if (!listProductCode.contains(productCode)) {
				listProductCode.add(productCode);
			}

			// 调出方库存解冻并出库
			{
				Long stockControlId = detail.getStockControlId();
				Integer num = detail.getNum();
				Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_FINISH.value;
				String sourceBid = entity.getBid();
				Long sourceId = detail.getId();
				tccStockControlService.thaw(stockControlId, num, sourceType, sourceBid, sourceId);
			}
			{
				Long stockControlId = detail.getStockControlId();
				String remark = "手工分配单：" + entity.getBid();
				Integer numOut = detail.getNum();
				String bidRelative = entity.getBid();
				Integer sourceType = TccStockSourceEnum.Source.TCC_Distribute.value;
				Long sourceId = detail.getId();
				tccStockControlService.outWithRunning(stockControlId, remark, numOut, bidRelative, sourceType,sourceId);
			}

			// 调入方库存新增
			TccStockControl tccStockControlFrom = new TccStockControl().setId(detail.getStockControlId()).queryFirst();
			{
				String rkBid = tccStockControlFrom.getRkBid();
				String productName = tccStockControlFrom.getProductName();
				Integer productNum = detail.getNum();
				Integer productNumAll = detail.getNum();
				BigDecimal purchasePrice = tccStockControlFrom.getPurchasePrice();
				BigDecimal purchaseTotalPriceAll = tccStockControlFrom.getPurchaseTotalPriceAll();
				BigDecimal allotPrice = tccStockControlFrom.getAllotPrice();
				BigDecimal totalAllotPrice = tccStockControlFrom.getTotalAllotPrice();
				String vgsbm = tccAllocateDetail.getVgsbmTo();
				Date drksj = tccStockControlFrom.getDrksj();
				Integer isParent = TccStockSourceEnum.IsParent.YES.value;
				String chw = tccStockControlFrom.getChw();
				String companyVid = null;
				String sourceBid = entity.getBid();
				Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_FINISH.value;
				String remark = "手工分配单：" + sourceBid;
				String assembleBid = storageMapper.getAssembleBidByStockControlId(detail.getStockControlId());
				Long sourceId = id;
				tccStockControlService.inWithRunning(rkBid, chw, productName, productNum, productCode, productNumAll, purchasePrice, purchaseTotalPriceAll, allotPrice, totalAllotPrice, vgsbm, drksj, isParent, sourceBid, sourceType, remark, companyVid, assembleBid,sourceId);
			}

			// 调入方账户扣减
			Date now = new Date();
			{
				BigDecimal amount = tccAllocateDetail.getSinglePrice().multiply(new BigDecimal(detail.getNum()));

				try {
					// 解冻调入方账户
					tcwAccountCountForCompanyService.thaw(tccAllocateDetail.getVgsbmTo(), amount,
							TcwOperateFrozenRunningEnum.DocumentType.TCC_Distribute.value,
							detail.getId(),
							entity.getBid(),
							null);
				}catch (Exception e){
					logger.error("手工分配单解冻流水失败：" +e.getMessage());
					return;
				}

				// 扣减调入方账户余额
				String vGsBm = tccAllocateDetail.getVgsbmTo();
				String vGsBmP = tccAllocateDetail.getVgsbmFrom();
				String vJyLx = TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name;
				BigDecimal fJe = amount.negate();
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);

			}

			TccAllocate tccAllocate = new TccAllocate().setBid(tccAllocateDetail.getBidAllocate()).queryFirst();
			if (tccAllocate.getType() == TccAllocateEnum.Type.JING_PIN.value) {
				BigDecimal amount = BigDecimal.ONE.multiply(new BigDecimal(detail.getNum()));

				// 扣减调入方账户余额到仓储部
				String vGsBm = tccAllocateDetail.getVgsbmTo();
				String vGsBmP = AppConstant.STOCK_VGSBM;
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_ZZ.name;
				BigDecimal fJe = amount.negate();
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);
			}

			// 调出方账户入账
			{
				BigDecimal amount = detail.getSinglePrice().multiply(new BigDecimal(detail.getNum()));
				String vGsBm = tccAllocateDetail.getVgsbmFrom();
				String vGsBmP = tccAllocateDetail.getVgsbmTo();
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_CG.name;
				BigDecimal fJe = amount;
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);

				//当资金划入公司为GS0893运营中心，则需要将该库存的调拨价-采购价*1.05，划入GS0641
				if (vGsBm.equals("GS0893") && tccStockControlFrom.getPurchasePrice()!=null){
					ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setVgsbm("GS0641").queryFirst();
					if (thrOperateCompanyApply == null){
						throw new RuntimeException("GS0641运营公司不存在!");
					}
					BigDecimal amountFw = (((detail.getSinglePrice().subtract(tccStockControlFrom.getPurchasePrice())).multiply(new BigDecimal(1.05))).multiply(new BigDecimal(detail.getNum()))).setScale(3, BigDecimal.ROUND_HALF_UP);
					vJyLx =  TransactionTypeEnum.BusinessType.CGFW_DLCGFWF.name;
					vGsBm = tccAllocateDetail.getVgsbmFrom();
					vGsBmP = thrOperateCompanyApply.getVgsbm();
					fJe = amountFw.negate();
					dJySj = now;
					dShSj = now;
					vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
					mName = null;
					mType = null;
					mNid = null;
					mBid = null;
					mGuid = null;
					writeTime = now;
					tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
							dShSj, vBz, entity.getBid(), writeTime);

					vGsBm = thrOperateCompanyApply.getVgsbm();
					vGsBmP = tccAllocateDetail.getVgsbmFrom();
					fJe = amountFw;
					tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompanyNoTrigger(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
							dShSj, vBz, entity.getBid(), writeTime);
				}

			}
			if (tccAllocate.getType() == TccAllocateEnum.Type.JING_PIN.value) {
				BigDecimal amount = BigDecimal.ONE.multiply(new BigDecimal(detail.getNum()));

				// 仓储部组装费入账
				String vGsBm = AppConstant.STOCK_VGSBM;
				String vGsBmP = tccAllocateDetail.getVgsbmTo();
				String vJyLx =  TransactionTypeEnum.BusinessType.TCC_Distribute_ZZ.name;
				BigDecimal fJe = amount;
				Date dJySj = now;
				Date dShSj = now;
				String vBz = "手工分配单," + entity.getBid() + "," + tccAllocateDetail.getProductCode() + "," + detail.getNum();
				String mName = null;
				Integer mType = null;
				String mNid = null;
				String mBid = null;
				String mGuid = null;
				Date writeTime = now;
				tcwAccountDetailedForCompanyService.addTcwAccountDetailedForCompany(vGsBm, vGsBmP, vJyLx, fJe, dJySj,
						dShSj, vBz, entity.getBid(), writeTime);
			}

		}

//		 统计精品的调拨总人次和调拨总数量
		for(String productCode : listProductCode) {
			storageMapper.updateTpBoutiqueNumBuyerAndNumSale(productCode);
		}
	}

	@Override
	@Transactional
	public R flowRefuse(Long id, String reason, String loginUserId) throws Exception {
		TccDistribute entity = new TccDistribute().setId(id).queryFirst();
		String bid = entity.getBid();
		R r = yspTaskService.flowRefuse(bid, reason, loginUserId);
		
		if (r.getCode() == R.Code.SUCCESS.value) {
			// 若流程退回到初始化状态，解冻可用库存
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				List<TccDistributeDetail> listTccDistributeDetail = new TccDistributeDetail().setBidDistribute(bid).queryList();
				for(TccDistributeDetail detail : listTccDistributeDetail) {
					TccStockControl tccStockControl = new TccStockControl().setId(detail.getStockControlId()).queryFirst();
					tccStockControl.setProductNum(tccStockControl.getProductNum() + detail.getNum());
					
					Long id2 = detail.getStockControlId();
					Integer num = detail.getNum();
					Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_REFUSE.value;
					String sourceBid = bid;
					Long sourceId = detail.getId();
					tccStockControlService.thaw(id2, num, sourceType, sourceBid, sourceId);
				}
			}
		}
		
		return R.ok("操作成功");
	}


	@Override
	@Transactional
	public R flowInit(Long id, String reason, String loginUserId) throws Exception {
		TccDistribute entity = new TccDistribute().setId(id).queryFirst();
		String bid = entity.getBid();
		R r = yspTaskService.flowInit(bid, reason, loginUserId);

		if (r.getCode() == R.Code.SUCCESS.value) {
			// 若流程退回到初始化状态，解冻可用库存
			YsProcInst ysProcInst = new YsProcInst().setBid(bid).queryFirst();
			if (ysProcInst.getStateFlow() == YsProcInstEnum.StateFlow.INIT.value) {
				List<TccDistributeDetail> listTccDistributeDetail = new TccDistributeDetail().setBidDistribute(bid).queryList();
				for(TccDistributeDetail detail : listTccDistributeDetail) {
					TccStockControl tccStockControl = new TccStockControl().setId(detail.getStockControlId()).queryFirst();
					tccStockControl.setProductNum(tccStockControl.getProductNum() + detail.getNum());

					Long id2 = detail.getStockControlId();
					Integer num = detail.getNum();
					Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_REFUSE.value;
					String sourceBid = bid;
					Long sourceId = detail.getId();
					tccStockControlService.thaw(id2, num, sourceType, sourceBid, sourceId);
				}
			}
		}

		return R.ok("操作成功");
	}
	
	/*
	 *  验证详情数据
	 *  1、分配数量不能高于待分配数量
	 *  2、分配数量不能高于库存数量
	 *  3、货位情况不能为空
	 */
	private R checkDetailJA(JSONArray detailJA,String vgsbm) {

		if (detailJA == null || detailJA.size() == 0) {
			return R.error("详情数据不能为空");
		} else {
			for (int i = 0; i < detailJA.size(); i++) {
				JSONObject detailJO = detailJA.getJSONObject(i);
				Long allocateDetailId = detailJO.getLong("allocateDetailId");
				if (allocateDetailId == null) {
					return R.error("第" + (i + 1) + "条,预约调拨详情ID不能为空");
				}
				String vhw = detailJO.getString("vhw");
				if (vhw == null || vhw == ""){
					return R.error("货位编码不允许为空!");
				}
				Integer num = detailJO.getInteger("num");
				TccAllocateDetail tccAllocateDetail = new TccAllocateDetail().setId(allocateDetailId).queryFirst();
				if (num == null || num <= 0) {
					return R.error("第" + (i + 1) + "条,分配数量不能为空且必须大于0");
				} else if (num > tccAllocateDetail.getMayDistributeNum()) {
					return R.error("第" + (i + 1) + "条,分配数量不得高于未分配数量");
				}
				
				// 库存可用数量
				Long stockControlId = detailJO.getLong("stockControlId");
				if (stockControlId == null) {
					return R.error("库存ID不能为空");
				}
				TccStockControl tccStockControl = new TccStockControl().setId(stockControlId).queryFirst();
				if (!tccStockControl.getProductCode().equals(tccAllocateDetail.getProductCode())) {
					return R.error("第" + (i + 1) + "条,无效的数据来源【001】");
				} else if (!tccStockControl.getGdepot().equals(tccAllocateDetail.getDepotName())) {
					return R.error("第" + (i + 1) + "条,来源有误，调拨仓库与数据不匹配");
				} else if (tccStockControl.getProductNum() < num) {
					return R.error("第" + (i + 1) + "条,分配数量不得高于库存数量");
				} else if (detailJO.getInteger("stockNumAll").intValue() != tccStockControl.getProductNum().intValue()) {
					return R.error("第" + (i + 1) + "条,无效的数据来源【002】");
				}
				
				// 库存归属
				if(new TccStockControl().setId(stockControlId).setVgsbm(vgsbm).count() == 0) {
					return R.error("只能从调出运营公司下的库存调取");
				}
			}
			
			return R.ok();
		}
	}

	@Override
	public JSONArray getAutoDetailJA(String bidAllocate) throws Exception {
		JSONArray JA = new JSONArray();
		TccAllocate tccAllocate = new TccAllocate().setBid(bidAllocate).queryFirst();
		// 尚未流转结束的话，无法自动生成
		if (tccAllocate.getEffectStock() != FlowEnum.EffectStock.EFFECTED.value) {
			return JA;
		}
		
		List<TccAllocateDetail> listTccAllocateDetail = new TccAllocateDetail().setBidAllocate(bidAllocate).queryList();
		for(TccAllocateDetail tccAllocateDetail : listTccAllocateDetail) {
			
			// 查找库存
			List<TccStockControl> listTccStockControl = new TccStockControl()
					.setGdepot(tccAllocateDetail.getDepotName())
					.setVgsbm(tccAllocateDetail.getVgsbmFrom())
					.setProductCode(tccAllocateDetail.getProductCode())
					.where("A.ProductNum > 0")
					.setOrderby("A.Id asc")
					.queryList();
			
			Integer unDistributedNum = storageMapper.countUnDistributedNumOfTccAllocateDetail(tccAllocateDetail.getId());
			for(TccStockControl tccStockControl : listTccStockControl) {
				JSONObject detailJO = new JSONObject();
				detailJO.put("allocateDetailId", tccAllocateDetail.getId());
				detailJO.put("singlePrice", tccAllocateDetail.getSinglePrice());
				detailJO.put("stockControlId", tccStockControl.getId());
				detailJO.put("stockNumAll", tccStockControl.getProductNum());
				
				/**
				 * 若可用数量高于未分配数量，则直接把未分配数量作为本次分配数量
				 */
				if (unDistributedNum <= tccStockControl.getProductNum()) {
					detailJO.put("num", unDistributedNum);
					JA.add(detailJO);
					break;
				} else {
					Integer num = tccStockControl.getProductNum();
					detailJO.put("num", num);
					JA.add(detailJO);
					unDistributedNum = unDistributedNum - num;
				}
			}
		}
		
		return JA;
	}


	//获取子列表数据
	@Override
	@Transactional
	public List<Map<String, Object>> getItemList(String bid) throws Exception{
		// 子列表配置信息
		List<Map<String, Object>> sonlist = new TccDistributeDetail()
				.setBidDistribute(bid)

				.addLeftJoin("TCC_AllocateDetail B ON B.Id = A.AllocateDetailId")
				.addField("B.BidAllocate bidAllocate")
				.addField("B.VgsbmFrom vgsbmFrom, B.VgsjcFrom vgsjcFrom")
				.addField("B.VgsbmTo vgsbmTo, B.VgsjcTo vgsjcTo")
				.addField("B.ProductCode productCode, B.ProductName productName")
				.addField("B.Num allocateNum, B.SinglePrice allocateSinglePrice,(B.Num * B.SinglePrice) allocateTotalPrice")
				.addField("B.DistributeNum distributedNum") // 已分配数量
				.addField("B.DistributeNum * B.SinglePrice distributedTotalPrice") // 已分配总额
				.addField("B.MayDistributeNum mayNum") // 未分配数量
				.addField("B.AllocateCancelNum canceledNum") // 已取消数量
				.addField("B.depotId depotId")
				.addField("B.depotName depotName")

				.addLeftJoin("TCC_StockControl C ON C.Id = A.StockControlId")
				.addField("C.VHw vhw")
				.addField("C.VKq vkq")
				.addField("C.GDepot gdepot")
				.addField("(SELECT tss.AssembleBid FROM TCC_StockControl tsc LEFT JOIN TCC_StockControlRunning tsr ON tsr.StockControlId = tsc.id LEFT JOIN TCC_StockSource tss ON tss.StockControlRunningId = tsr.id WHERE tsc.id = A.StockControlId AND tss.IsNewInventory = 1 AND tss.AssembleBid IS NOT NULL) bidProductAssemble")
				.queryMap();
		return sonlist;
	}

	/**
	 * 自动分配
	 */
	@Override
//	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public void automaticAllocation(TccAllocate tccAllocate) {
		try {
			List<TccAllocateDetail> tccAllocateDetailList = new TccAllocateDetail().setBidAllocate(tccAllocate.getBid()).queryList();
			if (tccAllocateDetailList.size() == 0){
				return;
			}
			Long createChangeId = 1030L;
			for (TccAllocateDetail tccAllocateDetail : tccAllocateDetailList){
				//只能分配对应公司名下的可用库存
				List<TccStockControl> tccStockControlList = new TccStockControl()
						.setVgsbm(tccAllocateDetail.getVgsbmFrom())
						.setProductCode(tccAllocateDetail.getProductCode())
						.setOrderby("A.Drksj ASC")
						.addLeftJoin("TCC_Location AA ON AA.Chw = A.Chw")
						.addLeftJoin("TCC_WarehouseArea BB ON BB.Ckq = AA.Ckq")
						.addLeftJoin("TCC_Warehouse CC ON CC.Cck = BB.Cck")
						.where("A.productNum > 0 AND CC.Cck = '" + tccAllocateDetail.getDepotId() + "'")
						.queryList();
				if (tccStockControlList.size() == 0){
					continue;
				}

				//新增手工分配单
				String bid = null;
				try {
					bid = commonApiService.getCommonNextBid(MenuId.TCC_Distribute);
				} catch (Exception e) {
					e.printStackTrace();
				}

				TccDistribute entity = new TccDistribute()
						.setBid(bid)
						.setType(TccDistributeEnum.Type.AUTO.value)
						.setVgsbm(tccAllocateDetail.getVgsbmFrom())
						.setCreateTime(new Date())
						.setEffectStock(0)
						.setVbz("系统自动分配!")
						.setCreateChangeId(createChangeId)
						.setStatus(1)
						;
				tccDistributeMapper.insert(entity);

				List<TccDistributeDetail> tccDistributeDetailList = new ArrayList<>();

				//在库天数时间长的先分配
				for(TccStockControl tccStockControl : tccStockControlList){
					if (tccAllocateDetail.getMayDistributeNum() == 0 && tccAllocateDetail.getStateDistribute() == 1){
						continue;
					}
					TccDistributeDetail tccDistributeDetail = new TccDistributeDetail()
							.setBidDistribute(bid)
							.setAllocateDetailId(tccAllocateDetail.getId())
							.setStockControlId(tccStockControl.getId())
							.setStockNumAll(tccStockControl.getProductNum())
							.setSinglePrice(tccAllocateDetail.getSinglePrice())
							.setStatus(1);
					//库存足够直接扣减
					if (tccStockControl.getProductNum() >= tccAllocateDetail.getMayDistributeNum()){
						tccDistributeDetail.setNum(tccAllocateDetail.getMayDistributeNum());
						tccAllocateDetail.setMayDistributeNum(0);
						tccAllocateDetail.setStateDistribute(1);
					}else {
						tccDistributeDetail.setNum(tccStockControl.getProductNum());
						tccAllocateDetail.setMayDistributeNum(tccAllocateDetail.getMayDistributeNum()-tccStockControl.getProductNum());
					}
					tccAllocateDetail.setDistributeNum(tccAllocateDetail.getDistributeNum()+tccDistributeDetail.getNum());
					tccDistributeDetailList.add(tccDistributeDetail);
				}
				tccAllocateDetailMapper.update(tccAllocateDetail);

				for (TccDistributeDetail tccDistributeDetail : tccDistributeDetailList){
					tccDistributeDetailMapper.insert(tccDistributeDetail);

					//冻结库存
					Integer sourceType = TccStockFrozenRunningEnum.SourceType.TCC_Distribute_FLOW_ADDZD.value;
					String sourceBid = bid;
					Long sourceId = tccDistributeDetail.getId();
					tccStockControlService.frozen(tccDistributeDetail.getStockControlId(), tccDistributeDetail.getNum(), sourceType, sourceBid, sourceId);
				}

				/*
				 * 流程初始化
				 */
				YsMenu ysMenu = new YsMenu().setId(MenuId.TCC_Distribute).queryFirst();
				if (ysMenu.getFlowModelId().longValue() != 0L) {
					YspModel yspModel = new YspModel().setId(ysMenu.getFlowModelId()).queryFirst();
					String codeModel = yspModel.getCode();
					yspTaskService.init(codeModel, bid, createChangeId.toString());
				}

				R r = flowPass(entity.getId(), createChangeId.toString());
				if (r.getCode() == R.Code.FAILED.value) {
					logger.error("自动生成分配单审核失败：单号"+tccAllocate.getBid(),r.getMsg());
					return;
				}
				logger.info("自动生成分配单：单号"+tccAllocate.getBid()+ "成功");
			}
		}catch (Exception e){
			logger.error("自动生成分配单失败：单号"+tccAllocate.getBid(),e.getMessage(),e);
		}

	}


}
